package g2.routemaster.gui.actions;

import g2.routemaster.gui.ApplicationStart;
import g2.routemaster.gui.BoardSingleton;
import g2.routemaster.gui.GManager;
import g2.routemaster.model.GameManager;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;

import de.tu_bs.coobra.LocalRepository;
import de.tu_bs.coobra_plugin.CoObRAPersistentObject;

public class LoadGameAction extends Action {
   private ApplicationWindow window;
   public LoadGameAction(ApplicationWindow window) {
      setText("Load Game");
      setToolTipText("Load Game");
      this.window = window;
   }

   public void run() {
      FileDialog dial = new FileDialog(window.getShell(), SWT.OPEN);
      String path = dial.open();
      if(path != null){
         GameManager gm = loadGameManager(path);
         
         GManager.instance().setGameManager(gm);
         ((ApplicationStart)window).createGamingBoard();
      }
      
      BoardSingleton.instance().updateAll();
   }

   /**
    * Load savegame from file
    * @param path Path of file
    * @return Loaded gamemanager
    */
   public GameManager loadGameManager(String path) {
      try {
         LocalRepository localRepository = new LocalRepository(path);
         CoObRAPersistentObject.setVMRepository(localRepository);
         localRepository = CoObRAPersistentObject.getVMRepository();
         GameManager gameManager = (GameManager) CoObRAPersistentObject.getVMRepository().getRootObject();
         CoObRAPersistentObject.getVMRepository().moveChangesIntoChangesBase();
         return gameManager;
      } catch (Exception e) {
         e.printStackTrace();
         System.out.print("Error on game load");
         return null;
      }

   }
}
